package com.bboyuglyk.bboy_music_box_2023;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity {

    private MethodChannel methodChannel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        methodChannel = new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(), "MEventChannel");

        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();
        if (Intent.ACTION_SEND.equals(action)) {
            if (type != null && type.startsWith("audio/")) {
                Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                File uriFile = new File(uri.getPath());
                String path = uriFile.getPath();
                String fileName = uriFile.getName();
//                FileBean fileBean=new FileBean(fileName,path);
//                methodChannel.invokeMethod("receive_file",new Gson().toJson(fileBean));

                String filePath = getApplicationContext().getFilesDir().getAbsolutePath() + File.separator + fileName;
                if (uri != null) {
                    try {
                        File outFile = new File(filePath);
                        InputStream inputStream = getContentResolver().openInputStream(uri);
                        FileOutputStream fos = new FileOutputStream(outFile);
                        byte[] buf = new byte[1024];
                        int readCount = 0;
                        while ((readCount = inputStream.read(buf)) != -1) {
                            fos.write(buf, 0, readCount);
                        }
                        fos.flush();
                        inputStream.close();
                        fos.close();

                        FileBean fileBean = new FileBean(fileName, filePath);
                        methodChannel.invokeMethod("receive_file", new Gson().toJson(fileBean));

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
